import cgi
import httplib
import urllib

# imports should be alphabetized
from collections import namedtuple
from django.utils import simplejson as json
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from xml.dom.minidom import parse, parseString

# project imports
from config import zotero
from servlets.base_handler import BaseHandler


class MainHandler(BaseHandler):

    template = "main.html"

    def get(self):
        dom = self.fetchContent(zotero.userid, zotero.apikey)
        keys = self.fetchKeys(dom)
        self.template_vars['items'] = items = self.fetchItems(dom, keys)
        self.template_vars['title'] = title = dom.getElementsByTagName("title")[0].firstChild.data
        self.fill_template()

    @classmethod
    def fetchContent(cls, userid, apikey):
        url = zotero.baseurl + "/items?content=json&key=" + apikey
        result = urlfetch.fetch(url)
        if result.status_code == httplib.OK:
            return parseString(result.content)
        else:
            return ""

    @classmethod
    def fetchKeys(cls, dom):
        domItemKeys = dom.getElementsByTagNameNS("http://zotero.org/ns/api", "key")
        return [itemKey.firstChild.data for itemKey in domItemKeys]

    @classmethod
    def fetchItems(cls, dom, keys):
        # Even though we request as JSON, it still comes back as XML and the actual JSON is stored inside the "content" node. - THIS IS SO GHETTO, WTF!
        # Each item in the Zotero library has its own content node.
        domItems = dom.getElementsByTagName("content")        
        items = []
        for domItem, itemKey in zip(domItems, keys):
            jsonObject = json.loads(domItem.firstChild.data)
            item = Source(
                key = itemKey,
                title = jsonObject["title"],
                author_first = jsonObject["creators"][0]["firstName"],
                author_last = jsonObject["creators"][0]["lastName"],
                isbn = jsonObject["ISBN"],
                place = jsonObject["place"],
                publisher = jsonObject["publisher"]
            )
            items.append(item)
        return items


Source = namedtuple("Source", "title author_first author_last isbn place publisher key")

class Citation(webapp.RequestHandler):

    def get(self):
        keys = cgi.FieldStorage()  # you should probably be using self.request.get(*) for this
        url = zotero.baseurl + "/items/" + keys["item"].value + "/?key=" + zotero.apikey + "&format=bib&style=" + keys["style"].value
        result = urlfetch.fetch(url)
        self.response.out.write(result.content)
		
class Bibliography(webapp.RequestHandler):

    def get(self):
        keys = cgi.FieldStorage()
        url = zotero.baseurl + "/items/?format=bib&key=" + zotero.apikey + "&style=" + keys["style"].value
        result = urlfetch.fetch(url)
        self.response.out.write(result.content)

app = webapp.WSGIApplication([
    ('/', MainHandler),
    ('/Citation', Citation),
    ('/Bibliography', Bibliography)
  ], debug=True)

if __name__ == '__main__':
    webapp.util.run_wsgi_app(app)